package com.jstyle.beatecg.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.jstyle.beatecg.R;
import com.jstyle.beatecg.activity.EcgWatchActivity;
import com.jstyle.beatecg.activity.HeartHistoryShareActivity;
import com.jstyle.beatecg.activity.ReportActivity;
import com.jstyle.beatecg.adapter.EcgHistoryAdapter;
import com.jstyle.beatecg.app.MyApplication;
import com.jstyle.beatecg.daoManager.HrvDataDaoManager;
import com.jstyle.beatecg.model.HrvData;
import com.jstyle.beatecg.model.MyBluetoothDevice;
import com.jstyle.beatecg.util.DateUtil;
import com.jstyle.beatecg.util.ImageUtils;
import com.jstyle.beatecg.util.LanguageHelp;
import com.jstyle.beatecg.util.SchedulersTransformer;
import com.jstyle.beatecg.util.ScreenUtils;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link EcgHistoryFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class EcgHistoryFragment extends DialogFragment implements EcgHistoryAdapter.EcgHistoryListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.listView_device)
    ListView listViewDevice;
    @BindView(R.id.bt_scan_device)
    Button btScanDevice;
    Unbinder unbinder;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    List<HrvData> hrvDataList;
    private OnFragmentInteractionListener mListener;
    private EcgHistoryAdapter ecgHistoryAdapter;


    public EcgHistoryFragment() {
        // Required empty public constructor
    }
    public void SettingList(List<HrvData> hrvDataList) {
        this. hrvDataList=hrvDataList;
    }
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment EcgHistoryFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static EcgHistoryFragment newInstance(String param1, String param2) {
        EcgHistoryFragment fragment = new EcgHistoryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //添加这一行
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = inflater.inflate(R.layout.fragment_blank, container, false);
        unbinder = ButterKnife.bind(this, view);
        initData();
        return view;
    }

    private void initData() {
        LanguageHelp.changeAppLanguage(getActivity());
        File file = new File(ImageUtils.ecgPath);
        if (!file.exists()) return;
        String[] fileList=null;
        if(null!=file.list()){
             fileList = file.list();
            Arrays.sort(fileList, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return DateUtil.getDefaultLongMi(o2)-DateUtil.getDefaultLongMi(o1)>0?1:-1;
                }
            });
        }
        if(null!=hrvDataList){
            ecgHistoryAdapter = new EcgHistoryAdapter(getActivity(), Soretlist(hrvDataList),this);
            listViewDevice.setAdapter(ecgHistoryAdapter);
        }

    }


    private List<HrvData> Soretlist(List<HrvData> devices){
        //使用冒泡排序算法
        for(int i=0;i<devices.size()-1;i++){
            for(int j=0;j<devices.size()-1-i;j++){
                if(DateUtil.getDefaultLongMi(devices.get(j).getTime())<DateUtil.getDefaultLongMi(devices.get(j+1).getTime())){
                    HrvData devive=devices.get(j);
                    devices.set(j, devices.get(j+1));
                    devices.set(j+1, devive);
                }
            }
        }
        return  devices;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.bt_scan_device,R.id.bt_delete_history})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.bt_scan_device:
                dismiss();
                break;
            case R.id.bt_delete_history:
                File dir = new File(ImageUtils.ecgPath);
                deleteAllFile(dir);
                HrvDataDaoManager.DeleteALL();
                break;
        }
    }

    private void deleteAllFile(File dir) {

        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete();
            else if (file.isDirectory())
                deleteAllFile(file);
        }
        ecgHistoryAdapter.clear();
    }





    Boolean havevalue;
    @Override
    public void onHistoryClick(HrvData fileName) {
        checkPermissionRequest();
        //有没有SD卡权限
        if(havevalue){
            share(fileName);
        }else{
            Toast.makeText(getActivity(),getActivity().getString(R.string.sdcard),Toast.LENGTH_SHORT).show();
        }
    }


    @SuppressLint("CheckResult")
    public void checkPermissionRequest() {
        RxPermissions rxPermission = new RxPermissions(getActivity());
        rxPermission.requestEach(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).subscribe(new Consumer<Permission>() {
            @Override
            public void accept(Permission permission) throws Exception {
                if (permission.granted) {
                    // 用户已经同意该权限
                    Log.e("wyl", permission.name + " is granted.");
                    havevalue=true;
                } else if (permission.shouldShowRequestPermissionRationale) {
                    // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时。还会提示请求权限的对话框
                    Log.e("wyl",permission.name + " is denied. More info should be provided.");
                    havevalue=false;
                } else {
                    // 用户拒绝了该权限，而且选中『不再询问』
                    Log.e("wyl", permission.name + " is denied.");
                    havevalue=false;
                }
            }
        });
    }
    @Override
    public void onWatchClick(HrvData hrvData) {
        toReport(hrvData);
    }


    private void toReport(HrvData hrvData){
        Intent intent = new Intent(getActivity(), ReportActivity.class);
        intent.putExtra("type","1");//当前默认为测量数据
        intent.putExtra("filepath", ImageUtils.ecgPath+hrvData.getTimetwo()+".ecg");
        startActivity(intent);
    }

    @Override
    public void onReplayClick(HrvData hrvData) {
        Intent intent = new Intent(getActivity(), EcgWatchActivity.class);
        intent.putExtra("type",EcgWatchActivity.RePlay);
        intent.putExtra("filepath", ImageUtils.ecgPath+hrvData.getTimetwo()+".ecg");
        startActivity(intent);
    }





    private List<Integer> data=new ArrayList<>();
    private long lastClickTime = 0L;
    // 两次点击间隔不能少于1000ms
    private static final int FAST_CLICK_DELAY_TIME = 1500;
    private void share(HrvData hrvData){
        File dir = new File(ImageUtils.pdfPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME){ return; }
        lastClickTime = System.currentTimeMillis();
        Uri imageUri = null;
        String time=DateUtil.getFormatTimeString(Long.valueOf(hrvData.getTimetwo()),"yyMMddHHmm");
        copyFile(ImageUtils.ecgPath+hrvData.getTimetwo()+".ecg",ImageUtils.ecgPath+"EK_"+time+".ecg");
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(MyApplication.context.getApplicationContext(),
                    getString(R.string.fileprovider), new File(ImageUtils.ecgPath+"EK_"+time+".ecg"));
        } else {
            imageUri = Uri.fromFile(new File(ImageUtils.ecgPath+"EK_"+time+".ecg"));
        }
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setType("text/plain");
        getActivity().startActivity(Intent.createChooser(shareIntent, getString(R.string.share)));
    }

    /**
     * oldPath 和 newPath必须是新旧文件的绝对路径
     * */
    public boolean copyFile(String oldPath$Name, String newPath$Name) {
        try {
            File oldFile = new File(oldPath$Name);
            if (!oldFile.exists()) {
                Log.e("--Method--", "copyFile:  oldFile not exist.");
                return false;
            } else if (!oldFile.isFile()) {
                Log.e("--Method--", "copyFile:  oldFile not file.");
                return false;
            } else if (!oldFile.canRead()) {
                Log.e("--Method--", "copyFile:  oldFile cannot read.");
                return false;
            }

            /* 如果不需要打log，可以使用下面的语句
            if (!oldFile.exists() || !oldFile.isFile() || !oldFile.canRead()) {
                return false;
            }
            */

            FileInputStream fileInputStream = new FileInputStream(oldPath$Name);
            FileOutputStream fileOutputStream = new FileOutputStream(newPath$Name);
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = fileInputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            fileInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    public void sharePdfByPhone(Context context, String path) {
        Uri imageUri = null;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(context.getApplicationContext(),
                    getString(R.string.fileprovider), new File(path));

        } else {
            imageUri = Uri.fromFile(new File(path));
        }
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setType("*/*");
        context.startActivity(Intent.createChooser(shareIntent, getString(R.string.share)));
    }
}
